package game_controller_config;

import g4p_controls.G4P;
import g4p_controls.GAlign;
import g4p_controls.GButton;
import g4p_controls.GCScheme;
import g4p_controls.GEvent;
import g4p_controls.GLabel;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

import org.gamecontrolplus.Configuration;
import org.gamecontrolplus.ControlDevice;
import org.gamecontrolplus.ControlIO;

import processing.core.PApplet;

public class Configurator extends PApplet {

	static {
		Configuration.IDE = Configuration.ECLIPSE;
	}
	
	ControlIO controlIO;
	int panelHeight;
	GLabel lblPath, lblSketch;
	GButton btnSelSketch;
	
	List<TSelectEntry> deviceEntries =  new ArrayList<TSelectEntry>();

	public void setup(){
		controlIO = ControlIO.getInstance(this);
		panelHeight = 100;
		int appHeight = controlIO.getNumberOfDevices() *20 + 40 + panelHeight;
		size(600,appHeight);
		G4P.messagesEnabled(true);                                                                             
		G4P.setGlobalColorScheme(GCScheme.GREEN_SCHEME);
		if(frame != null)
			frame.setTitle("Game Input Device Configurator");
		registerMethod("dispose", this);
		createSelectionInterface();
		List<ControlDevice> devices = controlIO.getDevices();
		// Add entries for devices added
		for(ControlDevice d : devices){
			if(d != null && !d.getTypeName().equalsIgnoreCase("keyboard"))
				deviceEntries.add(new TSelectEntry(this, controlIO, d));
		}
		// Reposition entries on screen
		for(int i = 0; i < deviceEntries.size(); i++)
			deviceEntries.get(i).setIndex(panelHeight + 20, i);
	}

	private void createSelectionInterface() {
		GLabel lblPathTag = new GLabel(this,0,0,100,20,"Sketch Path : ");
		lblPathTag.setOpaque(true);
		lblPathTag.setTextBold();		
		GLabel lblSketchTag = new GLabel(this,0,20,100,20,"Sketch Name : ");
		lblSketchTag.setOpaque(true);
		lblSketchTag.setTextBold();	
		
		lblPath = new GLabel(this,100,0,width-100,20);
		lblPath.setLocalColorScheme(G4P.PURPLE_SCHEME);
		lblPath.setOpaque(true);
		lblPath.setText(sketchPath(""));
		lblPath.setTextAlign(GAlign.LEFT, GAlign.MIDDLE);
		
		lblSketch = new GLabel(this,100,20,width-100,20);
		lblSketch.setLocalColorScheme(G4P.PURPLE_SCHEME);
		lblSketch.setOpaque(true);
		lblSketch.setText(getClass().getSimpleName() + ".pde");
		lblSketch.setTextAlign(GAlign.LEFT, GAlign.MIDDLE);

		btnSelSketch = new GButton(this,width-60,4,56,33, "Select Sketch");
		
		GLabel lblControls = new GLabel(this, 0, panelHeight, width, 20);
		lblControls.setText("Game Devices Available");
		lblControls.setOpaque(true);
		lblControls.setTextBold();		
	}

	public void handleButtonEvents(GButton button, GEvent event) { 
		if(button == btnSelSketch && event == GEvent.CLICKED){
			selectSketch();
		}
	}
	
	public void draw(){
		background(255, 255, 220);
		
		stroke(230, 230, 200);
		fill(240, 240, 210);
		int y = panelHeight;
		while(y < height){
			rect(0,y,width,20);
			y += 40;
		}

	}
	
	public void dispose(){
		System.out.println("Disposing");
		for(TSelectEntry entry : deviceEntries){
			if(entry.winCofig != null){
				entry.winCofig.close();
				entry.winCofig = null;
			}
		}
	}

	public void selectSketchORG(){
		JFileChooser chooser = new JFileChooser();
		chooser.setDialogTitle("Select sketch");
		chooser.setFileFilter(new SketchFileFilter());
		noLoop();
		int result = chooser.showOpenDialog(null);
		if (result == JFileChooser.APPROVE_OPTION) {
			File selected = chooser.getSelectedFile();
			if(selected.isFile()){
				TConfigUI.pathToSketch = selected.getParent();
				lblPath.setText(TConfigUI.pathToSketch);
				lblSketch.setText(selected.getName());
			}
		}
		loop();
	}
	
	public void selectSketch(){
		String selected = G4P.selectInput("Select main sketch (pde) file", "pde", "Processing sketch");
		if(selected != null){
			File file = new File(selected);
			// Get the name of the parent folder
			String sketchFolderName = file.getParent();
			// Get the filename without the extension
			String filename = file.getName();
			int index = filename.lastIndexOf('.');
			String sketchName = (index > 0 ) ? filename.substring(0,index) : filename;
			// See if we have selected the main sketch pde
			println(sketchFolderName);
			println(sketchName);
			
			if(sketchFolderName.endsWith(sketchName)){
				TConfigUI.pathToSketch = sketchFolderName;
				lblPath.setText(sketchFolderName);
				lblSketch.setText(filename);
			}
		}
	}

	public static class SketchFileFilter extends FileFilter {

		public SketchFileFilter(){}

		/**
		 * Get the extension of a file (make it lowercase
		 */
		public String getExtension(String name) {
			int index = name.lastIndexOf('.');
			return (index > 0 ) ? name.substring(index+1).toLowerCase() : "";
		}

		@Override
		public boolean accept(File f) {
			boolean ok = false;
			if(f.isDirectory())
				return true;
			if(f.isFile()){
				String name = f.getName();
				String ext = getExtension(name);
				if(ext.equals("pde")){
					String sketchName = name.substring(0, name.length()-4);
					ok = f.getParent().endsWith(sketchName);
				}
			}
			return ok;
		}

		@Override
		public String getDescription() {
			
			return "Find sketch folder";
		}

	}

}
